<script lang="ts" setup>
import { reactive,ref,computed } from 'vue'
import {ElMessage} from "element-plus";
const searchFrom = reactive({
  name: '',
  department: '',
  status: '',
  attendanceDate: '',
})
const currentPage = ref(1);
const pageSize = ref(10);

const departmentOptions = [
  { value: '技术部', label: '技术部' },
  { value: '销售部', label: '销售部' },
  { value: '财务部', label: '财务部' },
  { value: '市场部', label: '市场部' },
  { value: '人事部', label: '人事部' },
  { value: '行政部', label: '行政部' },
  { value: '其他部门', label: '其他部门' },
];
const statusOptions = [
  { value: '正常', label: '正常' },
  { value: '迟到', label: '迟到' },
  { value: '早退', label: '早退' },
  { value: '异常', label: '异常' },
  { value: '外勤', label: '外勤' },
  { value: '请假', label: '请假' },
  { value: '出差', label: '出差' },
  { value: '年假', label: '年假' },
  { value: '病假', label: '病假' },
]
const handleSearch = () => {
  console.log('搜索条件：', searchFrom);
  // 这里应该调用API获取筛选后的数据
  // 示例:
  // fetchData(searchForm)
};
const resetSearch = () => {
  searchFrom.name = '';
  searchFrom.department = '';
  searchFrom.status = '';
  searchFrom.attendanceDate = '';
};
const filteredTableData = computed(() => {
  return tableData.filter((item) => {
    // 姓名筛选
    if (searchFrom.name && !item.name.includes(searchFrom.name)) {
      return false
    }
    // 部门筛选
    if (searchFrom.department && item.department !== searchFrom.department) {
      return false
    }
    // 考勤状态筛选
    if (searchFrom.status && !item.status.includes(searchFrom.status)) {
      return false
    }
    // 日期筛选
    if (searchFrom.attendanceDate && item.attendanceDate !== searchFrom.attendanceDate) {
      return false
    }
    return true
  });

});
// 添加分页计算属性
const paginatedTableData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return filteredTableData.value.slice(start, end)
})
// 分页事件处理方法
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1 // 重置到第一页
}

const handleCurrentChange = (val: number) => {
  currentPage.value = val
}
const selectedRows = ref<any[]>([])
const handleSelectionChange = (val: any[]) => {
  selectedRows.value = val
}
const exportSelectedData = () => {
  if (selectedRows.value.length === 0){
    ElMessage.warning('请至少选择一条数据')
    return
  }
  const size =selectedRows.value.length
  ElMessage.success(`已选择${size}条数据，正在导出...`)
  exportToCSV(selectedRows.value, '考勤数据')
}
const exportToCSV = (data: any[], filename: string) => {
  if (data.length === 0) return;

  // 定义CSV表头和字段映射
  const headers = [
    '序号', '打卡人', '上班打卡时间', '下班打卡时间', '打卡方式',
    '打卡地点', '当天工作时长(小时)', '所属部门', '当天考勤状态', '备注', '当天日期'
  ];
  const fields = [
    'id', 'name', 'clockIn', 'clockOut', 'way',
    'locations', 'workHours', 'department', 'status', 'reason', 'attendanceDate'
  ];

  // 构建CSV内容
  let csvContent = '\uFEFF' + headers.join(',') + '\n'; // 添加UTF-8 BOM

  // 添加数据行
  data.forEach(item => {
    const row = fields.map(field => {
      const value = item[field];
      let processedValue = value;

      // 处理包含逗号或引号的值
      if (typeof processedValue === 'string' && (processedValue.includes(',') || processedValue.includes('"'))) {
        return `"${processedValue.replace(/"/g, '""')}"`;
      }
      // 处理undefined或null值
      if (processedValue === undefined || processedValue === null) {
        return '';
      }
      return processedValue;
    }).join(',');
    csvContent += row + '\n';
  });

  // 创建Blob对象
  const blob = new Blob([csvContent], { type: 'text/csv;charset=utf-8;' });

  // 创建下载链接
  const link = document.createElement('a');
  const url = URL.createObjectURL(blob);

  // 设置文件名
  const dateTime = new Date().toISOString().slice(0, 10);
  link.setAttribute('href', url);
  link.setAttribute('download', `${filename}_${dateTime}.csv`);
  link.style.visibility = 'hidden';

  // 触发下载
  document.body.appendChild(link);
  link.click();
  document.body.removeChild(link);
};
/**
 * 响应式表格数据集合
 *
 * 包含多个考勤记录对象，每条记录包括以下字段：
 * - id: 序号（number）
 * - clockIn: 打卡人姓名（string）
 * - time: 打卡时间（string）
 * - way: 打卡方式（string）
 * - locations: 打卡地点（string）
 * - source: 数据来源（string）
 * - clocking: 考勤组名称（string）
 * - status: 打卡状态（string）
 */
const tableData = reactive(
    [
        {
            id: 1,
          name: '小明',
          clockIn: '2024-06-12 9:04',
          clockOut: '2024-06-12 17:04',
            way: '地图',
            locations: '北京市海淀区',
          workHours: '8.5',
          department: '技术部',
            status: '正常 (外勤)',
          attendanceDate: '2024-06-12',
        },
        {
            id: 2,
          name: '张三',
          clockIn: '2023-06-12 9:04',
          clockOut: '2023-06-12 17:04',
            way: '地图',
            locations: '北京市海淀区',
          workHours: '8.5',
          department: '销售部',
            status: '迟到',
          attendanceDate: '2023-06-12',
        },
        {
            id: 3,
          name: '张三',
            clockIn: '2023-06-12 9:04',
          clockOut: '2023-06-12 17:04',
            way: '地图',
            locations: '北京市海淀区',
          workHours: '8.5',
          department: '财务部',
            status: '外勤',
          attendanceDate: '2023-06-12',
        },
        {
            id: 4,
          name: '张三',
            clockIn: '2023-06-12 9:04',
          clockOut: '2023-06-12 17:04',
            way: '地图',
            locations: '北京市海淀区',
          workHours: '8.5',
          department: '行政部',
            status: '请假',
          attendanceDate: '2025-11-16',
        },
    ]
)
</script>
<!-- 考勤信息 -->
<template>
    <div class="container">
        <!-- 卡片容器：用于展示考勤信息主界面 -->
        <el-card shadow="always" class="main-card">
            <!-- 标题区域 -->
            <div class="header-section">
                <span class="title">考勤信息</span>
            </div>
          <div class="search-and-actions">
            <!-- 搜索栏：输入姓名并进行搜索 -->
            <div class="search-controls">
              <el-input v-model="searchFrom.name" placeholder="请输入姓名" class="search-input" />
              <el-select v-model="searchFrom.department" placeholder="请选择部门" clearable class="filter-select">
                <el-option v-for="option in departmentOptions" :key="option.value" :value="option.value" :label="option.label" />
              </el-select>
              <el-date-picker v-model="searchFrom.attendanceDate" placeholder="请选择日期"  type="date" class="filter-select" format="YYYY-MM-DD" value-format="YYYY-MM-DD"/>
              <el-select v-model="searchFrom.status" placeholder="请选择考勤状态" clearable class="filter-select">
                <el-option v-for="option in statusOptions" :key="option.value" :value="option.value" :label="option.label" />
              </el-select>
              <el-button type="primary" class="search-button" @click="handleSearch">搜索</el-button>
              <el-button @click="resetSearch">重置</el-button>
            </div>
            <!-- 导出按钮 -->
                <el-button type="info" class="export-button" @click="exportSelectedData">导出</el-button>
          </div>
            <!-- 表格数据展示区 -->
            <el-table 
                :data="paginatedTableData"
                border 
                style="width: 100%" 
                :header-cell-style="{ textAlign: 'center' }"
                :cell-style="{ textAlign: 'center' }"
                class="clocking-table"
                @selection-change="handleSelectionChange"
            >
                <el-table-column type="selection" width="50" />
                <el-table-column prop="id" label="序号"  width="60"/>
                <el-table-column prop="name" label="打卡人"  min-width="80"/>
                <el-table-column prop="clockIn" label="上班打卡时间" min-width="100"/>
                <el-table-column prop="clockOut" label="下班打卡时间" min-width="100"/>
                <el-table-column prop="way" label="打卡方式"  width="90"/>
                <el-table-column prop="locations" label="打卡地点" min-width="70"/>
                <el-table-column prop="workHours" label="当天工作时长(小时)"  width="80" />
                <el-table-column prop="department" label="所属部门"  min-width="100"/>
                <el-table-column prop="status" label="当天考勤状态" min-width="120"/>
                <el-table-column prop="reason" label="备注" min-width="100"/>
                <el-table-column prop="attendanceDate" label="当天日期" min-width="100"/>
            </el-table>

            <!-- 分页控件 -->
            <div class="pagination-wrapper">
                <el-pagination
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="filteredTableData.length"
                    :page-sizes="[10, 20, 50, 100]"
                    :page-size="pageSize"
                    :current-page="currentPage"
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    class="mt-4" 
                />
            </div>
        </el-card>
    </div>
</template>
  
<style>





.table-wrapper {
  overflow-x: auto;
  margin-bottom: 20px;
}


/* 手机设备适配样式 */
@media (max-width: 768px) {


  .search-input-wrapper {
    width: 100%;
    justify-content: center;
  }

  .pagination-wrapper {
    justify-content: center;
  }
}
</style>
